package top.starmc.starpet.config

import org.bukkit.entity.Player
import taboolib.module.configuration.ConfigFile
import taboolib.module.database.ColumnOptionSQL
import taboolib.module.database.ColumnTypeSQL
import taboolib.module.database.Table
import taboolib.module.database.getHost

class MySQL(config: ConfigFile) {
    private val host = config.getHost("database")

    private val source by lazy { host.createDataSource() }

    private val table = Table(config.getString("database.table") ?: "starpet", host) {
        add("player") {
            type(ColumnTypeSQL.VARCHAR, 64) {
                options(ColumnOptionSQL.KEY)
                options(ColumnOptionSQL.PRIMARY_KEY)
            }
        }

        add("yaml") {
            type(ColumnTypeSQL.TEXT)
        }
    }

    init {
        table.createTable(source)
    }

    fun getData(player: Player): String? {
        return table.select(source) {
            rows("yaml")
            where("player" eq player.uniqueId.toString())
        }.firstOrNull {
            getString("yaml")
        }
    }

    fun saveData(player: Player, yaml: String) {
        val uuid = player.uniqueId.toString()
        table.insert(source, "player", "yaml") {
            value(uuid, yaml)
            onDuplicateKeyUpdate {
                update("yaml", yaml)
            }
        }
    }
}